#!/usr/bin/python
# -*- coding: utf-8 -*-
import pymysql


class dbOperate(object):

    def __init__(self, host, user, passwd, db, port=3306, charset='utf8'):  ##构造函数
        try:
            self.connection = pymysql.connect(host=host, user=user, passwd=passwd, db=db, autocommit=True)
            self.cur = self.connection.cursor()
        except Exception as e:
            # except:
            print('数据库连接失败:{}'.format(e))
            # print ('数据库连接失败')

    def exe_modify(self, sql, para):
        try:
            self.reConnect()
            self.cur.execute(sql, para)
            return self.cur.fetchall()
        except Exception as e:
            # except:
            print('sql语句有问题,{}'.format(sql))
            # print('sql语法错误')

    def exe_query(self, sql):
        try:
            self.reConnect()
            self.cur.execute(sql)
            return self.cur.fetchall()
        except Exception as e:
            # except:
            print('sql语句有问题,{}'.format(sql))
            # print('sql语法错误')

    def reConnect(self):
        """
         重连机制
         :return:
         """
        try:
            self.connection.ping()
        except:
            print('db is reconnecting')
            self.connection()

    def __del__(self):  # 析构函数,实例被销毁的时候执行
        self.cur.close()
        self.connection.close()
